<?php
declare (strict_types = 1);
namespace app\mall\model;
use app\order\model\OrderInfo;
use app\user\model\UserLevel;
use think\facade\Db;
use think\Model;

use app\common\model\BaseModel;
//use think\model\concern\SoftDelete;

Class ActivityLog extends BaseModel
{
//    use SoftDelete;
    // 软删除字段
//    protected $deleteTime = 'delete_time';
    // 软删除 默认值
//    protected $defaultSoftDelete = 0;

    public $error = '';
    public $field = 'id,oid,aid,uid,price,partake,miao,num,nums,end_time,add_time,pay_status,pid';

    /*预处理数据json*/
    public function getContentAttr($value){
        return $value ? json_decode($value,true) : $value;
    }

    /*预处理数据json*/
    public function getPartakeAttr($value){
        return $value ? json_decode($value,true) : $value;
    }

    /**
     * 根据订单生成新的历史记录活动log  和 当前的
     * @param $orderId  订单id  需要传递
     */
    public function createActivityData($data)
    {
        $data = [];
        $activityId = $this->insertGetId([
            'oid' => $data['orderId'], // 订单id
            'aid' => $data['aid'], // 活动id
            'uid' => $data['uid'], // 用户id
            'price' => $data['price'], // 金额分
            'partake' => $data['partake'], // 参与喵呗
            'miao' => $data['miao'], // 喵呗  单位分
            'num' => $data['num'], // 参与人数
            'numms' => $data['numms'], // 实际参与人数
            'end_time' => $data['end_time'], // 结束时间
            'add_time' => $data['add_time'], // 添加
            'pay_status' => $data['pay_status'], // 支付状态
            'pid' => $data['pid'] // 父级
        ]);
        if(!$activityId)
            return [400,'创建失败'];
        return [200,'创建ok'.$activityId];
    }

    /**
     * 我的活动列表
     * @param int $id  用户id
     * @return array
     */
    public function myActivityList($id)
    {
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            $where = ['ag.uid'=>$id,'ag.pay_status'=>1,'ag.is_delete'=>0];
            if(isset($data['astatus']) && strlen($data['astatus']) >= 1 && $data['astatus'] >= 0){
                $where['ag.astatus'] = $data['astatus'];
            }
            $limit = isset($data['limit'])&&!empty($data['limit']) ? $data['limit'] : 15;//每页显示数据
            $query = ['page' => (isset($data['page']) ? $data['page'] : 1)];//分页参数
            $field = 'a.id,ag.id as log_id,ag.oid,ag.num,ag.nums,a.name,a.title,a.cover,a.share,ag.price,ag.astatus,ag.add_time,ag.end_time';
            $item = $this->alias('ag')->join('activity a','a.id=ag.aid','left')->where($where)->field($field)->order('ag.add_time desc')->paginate($limit, false, array('query'=>$query));
            $data = empty($item) ? array():$item->toArray();
            if(!empty($data['data'])){
                $time = time();
                //只考虑已结束，不考虑已完成
                foreach($data['data'] as $k=>$v){
                    #if($v['end_time'] < $time) $data['data'][$k]['astatus'] = 2;
                    $data['data'][$k]['end_time'] = ($v['end_time']-$time)>0 ? $v['end_time']-$time : 0;
                    $data['data'][$k]['name'] = emojiDecode($v['name']);
                    $data['data'][$k]['title'] = emojiDecode($v['title']);
                    $data['data'][$k]['price'] = getformat($v['price']);
                    $data['data'][$k]['share'] = (checkFile($v['share']) == true) ? getApiDominUrl($v['share']) : getHostDominUrl($v['share']);
                    $data['data'][$k]['cover'] = (checkFile($v['cover']) == true) ? getApiDominUrl($v['cover']) : getHostDominUrl($v['cover']);
                    // 图片 字段拿取
                    if(isset($data['data'][$k]['img']) && $data['data'][$k]['img'] && strlen($data['data'][$k]['img']) >= 10){
                        $data['data'][$k]['cover'] = $data['data'][$k]['img'];
                        // 订单拿取 ---- 图片  --- 后期砍掉
                    }else if(isset($v['log_id']) && $v['log_id'] > 0){
                        $activityLogOne = ActivityLog::field('oid')->find($v['log_id']);
                        if($activityLogOne && $activityLogOne['oid'] && $activityLogOne['oid'] > 0){
                            $orderInfo = OrderInfo::where('oid',$activityLogOne['oid'])->find();
                            if($orderInfo && isset($orderInfo['json']['good_attr']) && isset($orderInfo['json'])){
                                $data['data'][$k]['cover'] = $orderInfo['json']['good_attr']['img'];
                            }
                        }
                    }
                }
            }
            return $data;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 我的活动详情
     * @param int $id  用户id
     * @return array
     */
    public function myActivityInfo($id)
    {
        try{
            if(empty($id)) exception('找不到该用户!');
            $datas = Input('post.');
            if(empty($datas['log_id'])) exception('找不到该活动记录!');
            $where = ['a.id'=>$datas['log_id'],'a.uid'=>$id,'a.pay_status'=>1,'a.is_delete'=>0];
            $field = 'a.aid,o.oid,a.partake,a.num,a.nums,g.name,g.title,g.share,a.end_time,o.json,a.goods_id';
            $item = $this->alias('a')->join('goods g','g.id=a.goods_id','left')->join('order_info o','o.oid=a.oid','left')->where($where)->field($field)->find();
            $data = empty($item) ? array():$item->toArray();
            if(!empty($data)){
                $data['share'] = (checkFile($data['share']) == true) ? getApiDominUrl($data['share']) : getHostDominUrl($data['share']);
                if($data['nums'] == $data['num']) $data['status'] = 1;
                elseif($data['end_time'] < time()) $data['status'] = 2;
                else $data['status'] = 0;
                if(!empty($data['json'])){
                    $data['json'] = is_array($data['json'])?$data['json']:json_decode($data['json'],true);
                    $data['json'] = $data['json']['good_attr'];
                    if(!empty($data['json']['valjson'][0])){
                        foreach($data['json']['valjson'][0] as $k=>$v){
                            $data['json']['valarray'][] = $k.'： '.$v;
                        }
                    }else $data['json']['valarray'] = [];
                }
                if(!empty($data['partake'])) $userMap = is_array($data['partake'])?$data['partake']:json_decode($data['partake'],true);
                $userMap[] = ['uid'=>$id];
                $uids = array_column($userMap, 'uid');
                $userList = Db::name('user')->whereIn('id',$uids)->field("id,nickname,avatarurl,IF(id={$id},1,0) as is_inviter")->select();
                $userList = empty($userList) ? array():$userList->toArray();
                $team = [];
                if(!empty($userList)){
                    foreach($uids as $v){
                        foreach($userList as $key=>$val){
                            if($val['is_inviter'] == 1) $team = $val;
                            elseif($val['id'] == $v)  $data['users'][] = $val;
                        }
                    }
                }
                else $data['users'] = [];
                if(!empty($data['users'])){
                    $data['users'] = array_reverse($data['users']);
                    array_push($data['users'],$team);
                }else $data['users'] = [$team];
                $data['end_time'] = ($data['end_time']-time())>0 ? $data['end_time']-time() : 0;
                unset($data['partake']);
            }
            $data['log_id'] = $datas['log_id'];
            return $data;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 视频分享-我的活动列表 进行中的
     * @param int $id  用户id
     * @return array
     */
    public function myActivityOngoing($user)
    {
        try{
            if(empty($user)) exception('找不到该用户!');
            $level = (new UserLevel())->where(['id'=>$user['level']])->find();
            if($level['share'] < 1) exception('暂无添加活动的权限，请提升会员等级!');
            $data = Input('post.');
            $where = [
                ['ag.uid','=',$user->id],
                ['ag.pay_status','=',1],
                ['ag.astatus','=',0],
                ['ag.end_time','>',time()],
                ['ag.is_delete','=',0],
            ];
            if(!empty($data['title'])){
                $where[] = ['a.name','like',trim($data['title']).'%'];
            }
            #设置已选择商品
            if(!empty($data['aid'])) $aid = $data['aid'];
            else $aid = 0;
            $field = 'a.id,ag.id as log_id,a.name,a.cover,ag.price,a.participate_num';
            $item = $this->alias('ag')->join('activity a','a.id=ag.aid','left')->where($where)->whereColumn('ag.nums','<','ag.num')->field($field)->order('ag.add_time desc')->select();
            $data = empty($item) ? array():$item->toArray();
            if(!empty($data)){
                //只考虑已结束，不考虑已完成
                foreach($data as $k=>$v){
                    $data[$k]['price'] = getformat($v['price']);
                    $data[$k]['share_commission'] = getformat( ($v['price']*$level['share'])/100 );
                    if($aid){
                        if($v['log_id'] == $aid) $data[$k]['select'] = 1;
                        else  $data[$k]['select'] = 2;
                    } else  $data[$k]['select'] = 0;
                }
            }
            return $data;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }
}